//
//  BoundConnectViewController.swift
//  EasePods
//
//  Created by 李然 on 2024/4/8.
//

import UIKit
import RxSwift
import RxCocoa
import MoyoungLib
import EarbudsFunctions
import Lottie
import SwiftEntryKit

class BoundConnectViewController: ViewController {
    
    let viewModel = BoundViewModel()
    
    override func makeUI() {
        super.makeUI()
        
        let backItem = UIBarButtonItem(image: R.image.ic_common_nav_back(), style: .plain, target: self, action: #selector(backAction))
        self.navigation.item.leftBarButtonItems = [backItem, UIBarButtonItem(customView: titleLabel)]
        
//        let scanButton = UIButton(type: .custom)
//        scanButton.setImage(R.image.ic_bound_qr(), for: .normal)
//        self.navigation.item.rightBarButtonItem = UIBarButtonItem(customView: scanButton)
//        scanButton.rx.tap
//            .subscribe(onNext: { [weak self] _ in
//                guard let `self` = self else { return }
//                
//            }).disposed(by: rx.disposeBag)
        
        view.addSubview(tipLabel)
        tipLabel.snp.makeConstraints { make in
            make.top.equalTo(navigation.bar.snp.bottom).offset(20)
            make.leading.equalTo(20)
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(tipLabel.snp.bottom).offset(20)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        view.addSubview(firstScanView)
        firstScanView.snp.makeConstraints { make in
            make.top.equalTo(navigation.bar.snp.bottom)
            make.leading.trailing.bottom.equalToSuperview()
        }
        
        view.addSubview(emptyView)
        emptyView.snp.makeConstraints { make in
            make.edges.equalTo(firstScanView)
        }
        
        emptyView.retryBtn.rx.tap.bind(to: reScan).disposed(by: rx.disposeBag)
        connectStatusView.retryBtn.rx.tap
            .subscribe(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                self.backAction()
            }).disposed(by: rx.disposeBag)
    }
    
    let reScan = PublishSubject<Void>()
    
    override func bindViewModel() {
        super.bindViewModel()
        
        let input = BoundViewModel.Input(reScan: self.reScan.asObservable())
        let output = self.viewModel.transform(input: input)
        
        output.dataSource.bind(to: self.tableView.rx.items(cellIdentifier: BoundDeviceCell.reuseIdentifier, cellType: BoundDeviceCell.self)) { _, item, cell in
            cell.bind(viewModel: item)
        }.disposed(by: rx.disposeBag)
        
        output.isSeaching.map{ !$0 }.bind(to: self.footView.rx.isHidden).disposed(by: rx.disposeBag)
        
        Observable.combineLatest(output.dataSource, output.isSeaching)
            .subscribe(onNext: { [weak self] viewModels, isSeaching in
                guard let `self` = self else { return }
                self.firstScanView.isHidden = true
                self.emptyView.isHidden = true
                if viewModels.isEmpty {
                    if isSeaching {
                        self.firstScanView.isHidden = false
                    } else {
                        self.emptyView.isHidden = false
                    }
                }
            }).disposed(by: rx.disposeBag)
        
        tableView.rx.modelSelected(BoundDeviceViewModel.self)
            .subscribe(onNext: { [weak self] viewModel in
                viewModel.connect.accept(())
                
                let vc = BoundGuideViewController()
                vc.guideType = .startEarPair
                vc.nextAction = {
                    let guide2 = BoundGuideViewController()
                    guide2.guideType = .setting
                    guide2.nextAction = {
                        guard UserDefaults.standard.bool(forKey: BoundGuideType.welcome.userDetaultKey) else {
                            UserDefaults.standard.setValue(true, forKey: BoundGuideType.welcome.userDetaultKey)
                            let welcomeVC = BoundGuideWelcomeViewController()
                            self?.navigationController?.pushViewController(welcomeVC, animated: true)
                            return
                        }
                        let nav = NavigationController(rootViewController: HomeViewController())
                        RootViewManager.default.transition(vc: nav)
                    }
                    self?.navigationController?.pushViewController(guide2, animated: true)
                }
                self?.navigationController?.pushViewController(vc, animated: true)
                
            }).disposed(by: rx.disposeBag)
    }
    
    lazy var tipLabel: UILabel = {
        let label = UILabel()
        label.text = R.string.localizable.bound_scan_click_tip()
        label.textColor = R.color.common_3_text()
        label.font = Fonts.systemFont(ofSize: 12)
        label.numberOfLines = 0
        return label
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.backgroundColor = .clear
        tableView.rowHeight = UITableView.automaticDimension
        tableView.sectionFooterHeight = 0
        tableView.sectionHeaderHeight = 0
        tableView.register(BoundDeviceCell.self, forCellReuseIdentifier: BoundDeviceCell.reuseIdentifier)
        tableView.tableFooterView = footView
        tableView.separatorStyle = .none
        tableView.contentInset = UIEdgeInsets(top: -10, left: 0, bottom: 0, right: 0)
        return tableView
    }()
    
    lazy var footView: BoundFooterView = {
        let footView = BoundFooterView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44))
        footView.titleLabel.text = R.string.localizable.bound_scanning()
        return footView
    }()
    
    lazy var emptyView: BoundEmptyView = {
        let view = BoundEmptyView()
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = R.string.localizable.bound_add_device_title()
        label.textColor = R.color.common_3_text()
        label.font = Fonts.systemFont(ofSize: 24, weight: .semibold)
        label.numberOfLines = 0
        label.textAlignment = .left
        return label
    }()

    lazy var firstScanView: View = {
        let view = View()
        view.backgroundColor = R.color.common_2_bg_page()
        
        let animationView = LottieAnimationView()
        let animation = LottieAnimation.named("ani_bound_scanning")
        animationView.animation = animation
        animationView.loopMode = .loop
        animationView.backgroundBehavior = .pauseAndRestore
        animationView.play()
        view.addSubview(animationView)
        animationView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: 300, height: 300))
        }
        return view
    }()
    
    lazy var connectStatusView: BoundConnectingView = {
        let view = BoundConnectingView()
        return view
    }()
}
